package com.androidjam.runningacoruna;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.Toast;

import com.androidjam.runningacoruna.Track.TYPE;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.readystatesoftware.mapviewballoons.BalloonItemizedOverlay;
import com.readystatesoftware.mapviewballoons.BalloonOverlayView;

public class RunningMapActivity extends MapActivity {
	
		
	static DescriptionOverlayItem staticItem;
	static TrackPathOverlay trackPathOverlay;
	MapView mapView;    
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
				this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_running_map);
			
		mapView = (MapView) findViewById(R.id.mapview);
		MapController mapController = mapView.getController();					   	

		trackPathOverlay = new TrackPathOverlay();
		
		mapController.setZoom(5);
		mapView.setBuiltInZoomControls(true);

		int lat = (int) (40.437998 * 1E6);
		int lng = (int) (-3.624458 * 1E6);
		mapController.setCenter(new GeoPoint(lat, lng));
		mapView.invalidate();

		Drawable generalDrawableDefault = getResources()
				.getDrawable(R.drawable.marker);
		Drawable generalDrawable = getResources()
				.getDrawable(R.drawable.runningeasy);		
		Drawable generalDrawable2 = getResources()
				.getDrawable(R.drawable.runninghard);
		Drawable generalDrawable3 = getResources()
				.getDrawable(R.drawable.runningironman);
		Drawable generalDrawable4 = getResources()
				.getDrawable(R.drawable.runningmedium);

		
		/*
		ArrayList<Track> trackList = FuncionalidadesServiceWeb.registros();
		
		if(trackList!=null){
			Log.i("RUNNINGMAPACTIVITY", "########################################## NO ES NULL");
		} else
		Log.i("RUNNINGMAPACTIVITY", "########################################## NULL @@@@@@@@@@@@@@@@@@2");
		
		*/
		List<Overlay> mapOverlays = mapView.getOverlays();							
		mapOverlays.add(new CustomItemizedOverlay(generalDrawable, mapView,Track.TYPE.RUNNING_EASY));
		mapOverlays.add(new CustomItemizedOverlay(generalDrawable2, mapView,Track.TYPE.RUNNING_HARD));
		mapOverlays.add(new CustomItemizedOverlay(generalDrawable3, mapView,Track.TYPE.RUNNING_IRONMAN));
		mapOverlays.add(new CustomItemizedOverlay(generalDrawable4, mapView,Track.TYPE.RUNNING_MEDIUM));				

		mapOverlays.add(trackPathOverlay);
		
	}
/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_running_map, menu);
		return true;
	}
*/
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}	

	private class CustomItemizedOverlay extends BalloonItemizedOverlay<DescriptionOverlayItem> {
		
		private Context context;
		private Drawable marker;		
		private Context c;
		private MapView mapView;
		private List<DescriptionOverlayItem> listDescriptionItems;		
		private long systemTime = System.currentTimeMillis();
		private static final float POINT_DIFFERENCE = 50;
		
		private float downX;
	    private float downY;
		

		public CustomItemizedOverlay(Drawable marker, MapView mapView, TYPE type) {				
			super(boundCenter(marker), mapView);
			c = mapView.getContext();							
			
			this.mapView = mapView;
			listDescriptionItems = new ArrayList<DescriptionOverlayItem>();
			this.context = context;
			this.marker = marker;
			
			int lat = (int) ((40.437998+10*type.ordinal()) * 1E6);
			int lng = (int) ((-3.624458) * 1E6);
			GeoPoint p = new GeoPoint(lat,lng);
			Track t = new Track("Track1", p,"Descripcion de track",type);
			t.setCalories(500+10*type.ordinal());
			t.setDistance(10+2*type.ordinal());
			t.setElevation(5+2*type.ordinal());
			t.setHeart_rythm(140+3*type.ordinal());
			t.setEstimatedTime(4815000+100*type.ordinal());			
			t.generateSamplePoints();			
			this.listDescriptionItems.add(new DescriptionOverlayItem(p, "Track1", "Descripcion de track", "http://www.nubiantrack.com/wp-content/uploads/2011/03/crash-test-Nissan-Primera.jpg",t));
			
			lat = (int) ((38.437998+12*type.ordinal()) * 1E6);
			lng = (int) ((-3.624458+3*type.ordinal()) * 1E6);
			p = new GeoPoint(lat,lng);
			Track t2 = new Track("Track2", p,"Descripcion de track2",type);
			t2.setCalories(600+10*type.ordinal());
			t2.setDistance(12+1*type.ordinal());
			t2.setElevation(3+2*type.ordinal());
			t2.setHeart_rythm(120+3*type.ordinal());
			t2.setEstimatedTime(2215000+200*type.ordinal());
			t2.generateSamplePoints();			
			this.listDescriptionItems.add(new DescriptionOverlayItem(p, "Track2", "Descripcion de track2", "http://www.sportbuild.com/images/track2a.jpg",t2));
			
			populate();
		}
		
		@Override
	    public boolean onTouchEvent(MotionEvent event, MapView mapV) {
	        switch (event.getAction()) {
	        case MotionEvent.ACTION_DOWN:
	            final long timeDiff = (System.currentTimeMillis() - systemTime);
	            if (timeDiff < ViewConfiguration.getDoubleTapTimeout()) 
	            {
	                if 
	                (
	                    (Math.abs(downX - event.getX()) < POINT_DIFFERENCE) && 
	                    (Math.abs(downY - event.getY()) < POINT_DIFFERENCE)
	                )
	                {
	                	MapController mpc = mapV.getController();
	                	mpc.zoomIn();
	            		/*Projection projection = mapV.getProjection();
	            		float latitud = event.getX();
	                    float longitud = event.getY();
	            		GeoPoint p = projection.fromPixels((int)latitud,(int)longitud);					
	            		mpc.setCenter(p);			
	            		
	            		mpc.animateTo(p);
	            		
	            		int zoomActual = mapV.getZoomLevel();
	            		 
	                    for(int i=zoomActual; i<10; i++)
	                        mpc.zoomIn();
	                    	zoomActual = mapV.getZoomLevel();
	            		*/
	                }            
	            }
	            break;
	        case MotionEvent.ACTION_UP:
	            systemTime = System.currentTimeMillis();
	            downX = event.getX();
	            downY = event.getY();
	            
	            break;
	        }
	        return false;        
	    }	
		
		
		
		public void addOverlay(DescriptionOverlayItem overlay) {
			listDescriptionItems.add(overlay);
		    populate();
		}

		@Override
		protected DescriptionOverlayItem createItem(int i) {			
			return listDescriptionItems.get(i);
		}

		@Override
		public int size() {
			return listDescriptionItems.size();
		}

		@Override
		protected boolean onBalloonTap(int index, DescriptionOverlayItem item) {
			
			Intent i = new Intent(RunningMapActivity.this,TrackDetailsActivity.class);			
			staticItem = listDescriptionItems.get(index);
			startActivity(i);
			return true;
		}
				
		@Override
		protected BalloonOverlayView<DescriptionOverlayItem> createBalloonOverlayView() {								
					
			// use our custom balloon view with our custom overlay item type:
			return new DescriptionBalloonOverlayView<DescriptionOverlayItem>(getMapView().getContext(), getBalloonBottomOffset());			
		}
		
		@Override
		protected void onBalloonOpen(int index) {					
			Track t = listDescriptionItems.get(index).getTrack();
			trackPathOverlay.setGeoPoints(t.getGeoPoints());
			
			MapController mapController = mapView.getController();
			mapController.setCenter(t.getPoint());
			mapController.animateTo(t.getPoint());
			mapController.setZoom(10);
			
			mapView.postInvalidate();
			Toast.makeText(c, "Item tap for overlay, value " + listDescriptionItems.get(index).getTitle()+"    GEOP: "+t.getGeoPoints().size(),
					Toast.LENGTH_LONG).show();
		}			
	}

}
